package com.wdh.kjs.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.DongTaiAdapter;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.DateUtilChange;
import com.wdh.kjs.util.DateUtils;
import com.wdh.kjs.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by feifei on 2016/4/27.
 */
public class DongtaiActivity extends BaseTopActivity {
    private Intent intent = new Intent();
    private PullToRefreshListView listView;
    private String partyId;
    private DongTaiAdapter noticeAdapter;
    private List<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();
    private HashMap<String, String> maps = new HashMap<String, String>();
    public static int page = 1;
    public static int rows = 10;
    private JsonModel jsonModel;
    public static int totalrecords = 0;
    public boolean mLoading = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.noticeactivity);
        SharedPreferences share = getSharedPreferences("logininfo", MODE_PRIVATE);
        partyId = share.getString("loginToken", "");
        page = 1;
        initview();
//        initwidge();
        intweb();
    }

    private void intweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_DONGTAI_ACTIVITY, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success) {
                    totalrecords = jsonModel.getTotalrecords();
                    initwidge();
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(DongtaiActivity.this, "网络异常！");
            }
        });

    }

    private void initview() {
        initTopBar("平台动态");
        listView = (PullToRefreshListView) findViewById(R.id.notice_listview);


    }

    private void initwidge() {
        noticeAdapter = new DongTaiAdapter(this, initListViewData());
        listView.setAdapter(noticeAdapter);
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {


            // 下拉Pulling Down
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);


                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();
            }

            // 上拉Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项

                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);


                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();


            }

        });

    }

    private List<HashMap<String, String>> initListViewData() {
        datas = new ArrayList<>();

        for (int i = 0; i < jsonModel.getPlatformTrendsList().size(); i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("title", jsonModel.getPlatformTrendsList().get(i).getTitle());
            String time = DateUtilChange.timestamp2String(jsonModel.getPlatformTrendsList().get(i).getCreatedStamp(), DateUtilChange.DEFAULT_DAY_FORMAT);
            hashMap.put("time",time);
            hashMap.put("userReceiveMessageId", jsonModel.getPlatformTrendsList().get(i).getPlatformTrendsId());
            datas.add(hashMap);
        }
        return datas;
    }


    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (totalrecords > datas.size()) {

                page += 1;
                try {
                    getMoreList();

                } catch (Exception e) {
                    page -= 1;
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            if (mLoading == false)
                ToastUtils.showShort(DongtaiActivity.this, "已无更多数据！");
            listView.onRefreshComplete();

            super.onPostExecute(aVoid);

        }
    }

    private void getMoreList() {
        RequestParams params = new RequestParams();

        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_DONGTAI_ACTIVITY, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success) {
                    if (jsonModel != null && jsonModel.getPlatformTrendsList().size() > 0) {

                        moreListViewData();
                    } else {
                        page -= 1;
                        ToastUtils.showShort(DongtaiActivity.this, "没有更多数据！");
                    }

                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(DongtaiActivity.this, "网络异常！");
            }
        });

    }

    private void moreListViewData() {
        for (int i = 0; i < jsonModel.getPlatformTrendsList().size(); i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("title", jsonModel.getPlatformTrendsList().get(i).getTitle());
            String time = DateUtilChange.timestamp2String(jsonModel.getPlatformTrendsList().get(i).getCreatedStamp(), DateUtilChange.DEFAULT_DAY_FORMAT);
            hashMap.put("time",time);
            hashMap.put("userReceiveMessageId", jsonModel.getPlatformTrendsList().get(i).getPlatformTrendsId());
            datas.add(hashMap);
        }
        if (datas.size() == totalrecords)
            mLoading = false;
        noticeAdapter.notifyDataSetChanged();
    }
}
